package com.swehr.servlet;

import com.swehr.model.Organization;
import com.swehr.model.ResultInfo;
import com.swehr.proxy.PersonnelServiceProxy;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author Rock Huang
 * @version 0.1
 */
public class OrganizationServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        ServletUtils.printRequestInfo(req);
        if (ServletUtils.toSignin(req, resp)) return;

        req.setAttribute("checked", "Organization"); // current checked module

        // showing Organization list

        // forward
        ServletUtils.forward(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        ServletUtils.printRequestInfo(req);
        ObjectMapper mapper = new ObjectMapper();
        String json = req.getParameter("carrier");
        List<Organization> orgs = mapper.readValue(json, new TypeReference<List<Organization>>(){});

//        for (Organization o: orgs) {
//            if (o.getId()==0) System.out.println("Created: \n ================");
//            else if (o.getId()>0) System.out.println("Updated \n ===============");
//            else if (o.getId() == -1) System.out.println("Delete \n ===============");
//            else {System.out.println("unexpected data");}
//            System.out.println(o.toString());
//        }

        ResultInfo rs = new PersonnelServiceProxy().save(orgs);
        resp.getWriter().println(rs.toString());
    }

    protected void doPut(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        ServletUtils.printRequestInfo(req);
    }

    protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        ServletUtils.printRequestInfo(req);
    }
}
